//
//  TodayView.swift
//  bill
//
//  Created by Eudon on 2025/6/18.
//

import SwiftUI
import UIKit

struct TodayView: View {
    @ObservedObject var store: TransactionStore
    @State private var showingAddTransaction = false
    @State private var billText: String = ""
    @State private var recognitionResult: (amount: Double, category: String, type: Transaction.TransactionType, note: String)? = nil
    
    // 获取今日交易
    private var todayTransactions: [Transaction] {
        store.todayTransactions()
    }
    
    // 计算当日收入
    private var dailyIncome: Double {
        todayTransactions.filter { $0.type == .income }.reduce(0) { $0 + $1.amount }
    }
    
    // 计算当日支出
    private var dailyExpense: Double {
        todayTransactions.filter { $0.type == .expense }.reduce(0) { $0 + $1.amount }
    }
    
    var body: some View {
        ScrollView {
            VStack(spacing: 24) {
                // 统计卡片
                VStack(spacing: 20) {
                    Text("今日统计")
                        .font(.system(size: 18, weight: .semibold))
                        .foregroundColor(Color(.label))
                        .padding(.bottom, 4)
                    HStack(spacing: 40) {
                        VStack(spacing: 8) {
                            Text("收入")
                                .font(.system(size: 14, weight: .medium))
                                .foregroundColor(Color(.secondaryLabel))
                            Text("¥\(dailyIncome, specifier: "%.2f")")
                                .font(.system(size: 20, weight: .semibold))
                                .foregroundColor(Color(red: 0.3, green: 0.8, blue: 0.4))
                        }
                        Divider()
                            .frame(height: 50)
                            .background(Color(.separator))
                        VStack(spacing: 8) {
                            Text("支出")
                                .font(.system(size: 14, weight: .medium))
                                .foregroundColor(Color(.secondaryLabel))
                            Text("¥\(dailyExpense, specifier: "%.2f")")
                                .font(.system(size: 20, weight: .semibold))
                                .foregroundColor(Color(red: 0.9, green: 0.3, blue: 0.3))
                        }
                    }
                }
                .padding(.horizontal, 24)
                .padding(.vertical, 28)
                .background(
                    RoundedRectangle(cornerRadius: 16)
                        .fill(Color(.systemBackground))
                        .shadow(color: Color.black.opacity(0.08), radius: 8, x: 0, y: 2)
                )
                .padding(.horizontal, 20)

                // 自动识别卡片恢复原有风格
                VStack(alignment: .leading, spacing: 16) {
                    Text("粘贴账单信息快速录入")
                        .font(.system(size: 16, weight: .semibold))
                        .foregroundColor(Color(.label))
                        .padding(.top, 4)
                    TextEditor(text: $billText)
                        .font(.system(size: 15))
                        .frame(height: 80)
                        .padding(10)
                        .background(RoundedRectangle(cornerRadius: 10).fill(Color(.systemGray6)))
                        .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color(.systemGray4)))
                        .padding(.bottom, 4)
                    Button(action: {
                        let result = parseBillText(billText)
                        recognitionResult = (result.amount, result.category, result.type, result.note)
                        showingAddTransaction = true
                        billText = ""
                    }) {
                        Text("自动识别")
                            .font(.system(size: 16, weight: .semibold))
                            .foregroundColor(.white)
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 14)
                            .background(
                                LinearGradient(
                                    gradient: Gradient(colors: [Color(.systemBlue), Color(.systemBlue).opacity(0.8)]),
                                    startPoint: .leading,
                                    endPoint: .trailing
                                )
                            )
                            .cornerRadius(10)
                            .shadow(color: Color(.systemBlue).opacity(0.15), radius: 4, x: 0, y: 2)
                    }
                }
                .padding(.horizontal, 20)

                // 明细卡片恢复原有风格
                VStack(alignment: .leading, spacing: 20) {
                    HStack {
                        Text("今日明细")
                            .font(.system(size: 18, weight: .semibold))
                            .foregroundColor(Color(.label))
                        Spacer()
                    }
                    .padding(.horizontal, 20)
                    if todayTransactions.isEmpty {
                        VStack(spacing: 16) {
                            Image(systemName: "calendar.badge.plus")
                                .font(.system(size: 48))
                                .foregroundColor(Color(.tertiaryLabel))
                            Text("今天还没有记录")
                                .font(.system(size: 16, weight: .medium))
                                .foregroundColor(Color(.secondaryLabel))
                        }
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 40)
                    } else {
                        VStack(spacing: 12) {
                            ForEach(todayTransactions) { transaction in
                                HStack(spacing: 16) {
                                    ZStack {
                                        Circle()
                                            .fill(transaction.type == .income ? 
                                                  Color(red: 0.3, green: 0.8, blue: 0.4).opacity(0.15) : 
                                                  Color(red: 0.9, green: 0.3, blue: 0.3).opacity(0.15))
                                            .frame(width: 44, height: 44)
                                        Text(transaction.type == .income ? "入" : "出")
                                            .font(.system(size: 18, weight: .bold))
                                            .foregroundColor(transaction.type == .income ? 
                                                           Color(red: 0.3, green: 0.8, blue: 0.4) : 
                                                           Color(red: 0.9, green: 0.3, blue: 0.3))
                                    }
                                    VStack(alignment: .leading, spacing: 4) {
                                        Text(transaction.category)
                                            .font(.system(size: 16, weight: .medium))
                                            .foregroundColor(Color(.label))
                                        if let note = transaction.note {
                                            Text(note)
                                                .font(.system(size: 14))
                                                .foregroundColor(Color(.secondaryLabel))
                                        }
                                    }
                                    Spacer()
                                    Text(transaction.type == .income ? "+¥\(transaction.amount, specifier: "%.2f")" : "-¥\(transaction.amount, specifier: "%.2f")")
                                        .font(.system(size: 16, weight: .semibold))
                                        .foregroundColor(transaction.type == .income ? 
                                                       Color(red: 0.3, green: 0.8, blue: 0.4) : 
                                                       Color(red: 0.9, green: 0.3, blue: 0.3))
                                }
                                .padding(.horizontal, 20)
                                .padding(.vertical, 16)
                                .background(
                                    RoundedRectangle(cornerRadius: 12)
                                        .fill(Color(.systemBackground))
                                        .shadow(color: Color.black.opacity(0.04), radius: 4, x: 0, y: 1)
                                )
                                .padding(.horizontal, 20)
                            }
                        }
                    }
                }
                .padding(.vertical, 20)
            }
            .padding(.vertical, 20)
        }
        .background(Color(.systemGroupedBackground))
        .navigationTitle("今天")
        .navigationBarTitleDisplayMode(.large)
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button(action: {
                    recognitionResult = nil
                    showingAddTransaction = true
                }) {
                    Image(systemName: "plus.circle.fill")
                        .font(.system(size: 24))
                        .foregroundColor(Color(.systemBlue))
                }
            }
        }
        .sheet(isPresented: $showingAddTransaction) {
            AddTransactionView(store: store, recognitionResult: recognitionResult)
        }
        .onTapGesture {
            // 点击外部收起键盘
            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
        }
    }
}

struct AddTransactionView: View {
    @Environment(\.dismiss) var dismiss
    @ObservedObject var store: TransactionStore
    var recognitionResult: (amount: Double, category: String, type: Transaction.TransactionType, note: String)? = nil
    @State private var amount = ""
    @State private var category = "房租"
    @State private var type: Transaction.TransactionType = .expense
    @State private var note = ""
    // 固定分类
    let allCategories = ["房租", "工资", "购物", "娱乐", "宠物", "生活缴费", "餐饮", "其他"]
    // 收入/支出类型关键词库增强
    let incomeKeywords = [
        "收入", "收款", "入账", "到账", "退款", "返现", "红包", "转入", "工资", "奖金", "进账", "转账收入", "利息", "分红", "奖励", "补贴", "报销", "返利", "提现成功", "转账到账", "收钱", "收", "奖金到账", "工资到账", "收钱码", "收款码", "提现到账", "工资收入", "兼职收入", "奖金收入", "投资收益", "理财收益", "分红收入", "报销收入", "补贴收入", "津贴收入", "返现收入", "佣金收入", "奖励收入", "红包收入", "退款收入", "转账收入", "借入", "借款收入", "利息收入", "奖金发放", "工资发放", "工资结算", "工资转账", "工资卡", "工资条", "理财赎回", "理财转入", "理财到账", "理财分红", "理财收益", "股息", "分红", "奖金", "津贴", "补助", "补贴", "补发", "补偿", "补助金", "补贴金", "补发工资", "补发奖金", "补发津贴", "补发补贴", "补发补助", "补发补偿", "补发补助金", "补发补贴金", "补发补发工资", "补发补发奖金", "补发补发津贴", "补发补发补贴", "补发补发补助", "补发补发补偿", "补发补发补助金", "补发补发补贴金", "补发补发补发工资", "补发补发补发奖金", "补发补发补发津贴", "补发补发补发补贴", "补发补发补发补助", "补发补发补发补偿", "补发补发补发补助金", "补发补发补发补贴金", "卖", "卖了", "卖出", "闲鱼卖", "闲鱼卖出", "二手卖", "二手卖出", "转卖", "转卖出", "转手", "转手卖", "转手卖出"
    ]
    let expenseKeywords = [
        "支出", "扣费", "消费", "购买", "付款", "转账", "充值", "出账", "转出", "支付", "付款成功", "消费支出", "购物支出", "转账支出", "提现", "还款", "缴费", "扣款", "支付成功", "买", "花费", "支出", "转账给", "转账到", "充值成功", "缴纳", "缴", "交", "买单", "买入", "信用卡还款", "还信用卡", "借出", "借款支出", "借款转出", "借款还款", "借款支付", "借款消费", "借款购物", "借款转账", "借款提现", "借款还款", "借款缴费", "借款扣款", "借款买单", "借款买入", "借款信用卡还款", "还信用卡", "借款借出", "借款借款支出", "借款借款转出", "借款借款还款", "借款借款支付", "借款借款消费", "借款借款购物", "借款借款转账", "借款借款提现", "借款借款还款", "借款借款缴费", "借款借款扣款", "借款借款买单", "借款借款买入", "借款借款借款信用卡还款", "借款借款借款还信用卡", "借款借款借款借出", "借款借款借款借款支出", "借款借款借款借款借款转出", "借款借款借款借款借款还款", "借款借款借款借款借款支付", "借款借款借款借款借款消费", "借款借款借款借款借款购物", "借款借款借款借款借款借款转账", "借款借款借款借款借款借款提现", "借款借款借款借款借款借款还款", "借款借款借款借款借款借款缴费", "借款借款借款借款借款借款扣款", "借款借款借款借款借款借款买单", "借款借款借款借款借款借款买入", "借款借款借款借款借款借款信用卡还款", "借款借款借款借款借款借款还信用卡", "借款借款借款借款借款借款借出"
    ]
    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("交易信息").font(.system(size: 16, weight: .semibold))) {
                    TextField("金额", text: $amount)
                        .keyboardType(.decimalPad)
                        .font(.system(size: 16))
                    Picker("类型", selection: $type) {
                        Text("支出").tag(Transaction.TransactionType.expense)
                        Text("收入").tag(Transaction.TransactionType.income)
                    }
                    .pickerStyle(.segmented)
                    Picker("类别", selection: $category) {
                        ForEach(allCategories, id: \.self) {
                            Text($0)
                        }
                    }
                    TextField("备注", text: $note)
                        .font(.system(size: 16))
                }
                Section {
                    Button("添加") {
                        if let amountValue = Double(amount) {
                            let newTransaction = Transaction(
                                amount: amountValue,
                                category: category,
                                date: Date(),
                                type: type,
                                note: note.isEmpty ? nil : note
                            )
                            store.addTransaction(newTransaction)
                            dismiss()
                        }
                    }
                    .disabled(amount.isEmpty)
                    .font(.system(size: 16, weight: .semibold))
                    .foregroundColor(amount.isEmpty ? Color(.tertiaryLabel) : Color(.systemBlue))
                }
            }
            .navigationTitle("添加交易")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        dismiss()
                    }
                    .foregroundColor(Color(.systemBlue))
                }
            }
            .onTapGesture {
                // 点击外部收起键盘
                UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
            }
        }
        .onAppear {
            if let result = recognitionResult {
                amount = String(result.amount)
                category = result.category
                type = result.type
                note = result.note
            }
        }
    }
}

#Preview {
    NavigationView {
        TodayView(store: TransactionStore())
    }
}

// 账单文本解析函数
func parseBillText(_ text: String) -> (amount: Double, category: String, type: Transaction.TransactionType, note: String) {
    // 收入/支出类型关键词库增强
    let incomeKeywords = [
        "收入", "收款", "入账", "到账", "退款", "返现", "红包", "转入", "工资", "奖金", "进账", "转账收入", "利息", "分红", "奖励", "补贴", "报销", "返利", "提现成功", "转账到账", "收钱", "收", "奖金到账", "工资到账", "收钱码", "收款码", "提现到账", "工资收入", "兼职收入", "奖金收入", "投资收益", "理财收益", "分红收入", "报销收入", "补贴收入", "津贴收入", "返现收入", "佣金收入", "奖励收入", "红包收入", "退款收入", "转账收入", "借入", "借款收入", "利息收入", "奖金发放", "工资发放", "工资结算", "工资转账", "工资卡", "工资条", "理财赎回", "理财转入", "理财到账", "理财分红", "理财收益", "股息", "分红", "奖金", "津贴", "补助", "补贴", "补发", "补偿", "补助金", "补贴金", "补发工资", "补发奖金", "补发津贴", "补发补贴", "补发补助", "补发补偿", "补发补助金", "补发补贴金", "补发补发工资", "补发补发奖金", "补发补发津贴", "补发补发补贴", "补发补发补助", "补发补发补偿", "补发补发补助金", "补发补发补贴金", "补发补发补发工资", "补发补发补发奖金", "补发补发补发津贴", "补发补发补发补贴", "补发补发补发补助", "补发补发补发补偿", "补发补发补发补助金", "补发补发补发补贴金", "卖", "卖了", "卖出", "闲鱼卖", "闲鱼卖出", "二手卖", "二手卖出", "转卖", "转卖出", "转手", "转手卖", "转手卖出"
    ]
    let expenseKeywords = [
        "支出", "扣费", "消费", "购买", "付款", "转账", "充值", "出账", "转出", "支付", "付款成功", "消费支出", "购物支出", "转账支出", "提现", "还款", "缴费", "扣款", "支付成功", "买", "花费", "支出", "转账给", "转账到", "充值成功", "缴纳", "缴", "交", "买单", "买入", "信用卡还款", "还信用卡", "借出", "借款支出", "借款转出", "借款还款", "借款支付", "借款消费", "借款购物", "借款转账", "借款提现", "借款还款", "借款缴费", "借款扣款", "借款买单", "借款买入", "借款信用卡还款", "还信用卡", "借款借出", "借款借款支出", "借款借款转出", "借款借款还款", "借款借款支付", "借款借款消费", "借款借款购物", "借款借款转账", "借款借款提现", "借款借款还款", "借款借款缴费", "借款借款扣款", "借款借款买单", "借款借款买入", "借款借款借款信用卡还款", "借款借款借款还信用卡", "借款借款借款借出", "借款借款借款借款支出", "借款借款借款借款借款转出", "借款借款借款借款借款还款", "借款借款借款借款借款支付", "借款借款借款借款借款消费", "借款借款借款借款借款购物", "借款借款借款借款借款借款转账", "借款借款借款借款借款借款提现", "借款借款借款借款借款借款还款", "借款借款借款借款借款借款缴费", "借款借款借款借款借款借款扣款", "借款借款借款借款借款借款买单", "借款借款借款借款借款借款买入", "借款借款借款借款借款借款信用卡还款", "借款借款借款借款借款借款还信用卡", "借款借款借款借款借款借款借出"
    ]
    // 1. 分割片段
    let separators = CharacterSet(charactersIn: ",，、.。 ;；:：\n\t ")
    let segments = text.components(separatedBy: separators).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
    
    // 2. 分类关键词库
    let categoryKeywords: [String: [String]] = [
        "房租": ["房租", "租金", "房东", "租房", "押金", "租赁", "房屋租赁", "房屋", "租期", "房费", "租金支付", "房租缴纳"],
        "工资": ["工资", "薪资", "薪水", "发薪", "工资到账", "奖金", "提成", "津贴", "补贴", "报销", "工资收入", "奖金收入", "工资发放", "工资结算", "工资转账", "工资卡", "工资条"],
        "购物": ["购物", "买", "购买", "消费", "淘宝", "天猫", "京东", "拼多多", "苏宁", "唯品会", "国美", "网易严选", "考拉", "超市", "便利店", "服饰", "化妆品", "护肤", "家电", "数码", "文具", "办公", "小米", "苹果", "华为", "优衣库", "ZARA", "H&M", "宜家", "屈臣氏", "名创优品", "山姆", "Costco", "盒马", "美团优选", "京喜", "抖音电商", "快手电商"],
        "娱乐": ["娱乐", "电影", "游戏", "KTV", "酒吧", "网吧", "爱奇艺", "腾讯视频", "优酷", "B站", "抖音", "快手", "直播", "会员", "演唱会", "彩票", "唱歌", "K歌", "剧本杀", "密室逃脱", "狼人杀", "剧院", "游乐场", "电玩城", "桌游", "Switch", "PS5", "XBOX", "Steam", "腾讯体育", "网易云音乐", "QQ音乐"],
        "宠物": ["宠物", "猫", "狗", "宠物医院", "宠物店", "宠物用品", "宠物粮", "宠物美容", "宠物保险", "宠物洗澡", "宠物疫苗", "宠物驱虫", "宠物寄养", "宠物玩具", "宠物零食", "宠物训练"],
        "生活缴费": ["水费", "电费", "燃气费", "物业费", "取暖费", "宽带费", "网费", "有线电视费", "垃圾费", "停车费", "生活缴费", "缴费", "缴纳", "交费", "水电费", "煤气费", "燃气缴费", "电费充值", "水费充值", "燃气充值", "物业管理费"],
        "餐饮": ["餐饮", "吃饭", "饭", "早餐", "午餐", "晚餐", "夜宵", "外卖", "美团", "饿了么", "肯德基", "麦当劳", "必胜客", "星巴克", "海底捞", "呷哺", "小肥羊", "喜茶", "奈雪", "瑞幸", "火锅", "烧烤", "自助餐", "快餐", "面馆", "米线", "拉面", "川菜", "湘菜", "粤菜", "西餐", "日料", "韩餐", "甜品", "奶茶", "饮品", "咖啡", "餐厅", "食堂", "聚餐", "聚会", "请客", "请吃饭", "聚餐费", "饭店", "酒楼", "酒馆", "小吃", "零食", "点心", "外带", "堂食", "团购", "美食"],
        "其他": ["其他", "杂项", "未知", "未分类", "其它", "其他支出", "其他收入"]
    ]
    // 3. 金额提取
    var amount: Double? = nil
    var amountSegmentType: Transaction.TransactionType? = nil
    var categoryScores: [String: Int] = [:]
    for seg in segments {
        // 金额识别
        if amount == nil, let num = extractNumber(seg) { amount = num
            // 类型判断增强
            let lowerSeg = seg.lowercased()
            if incomeKeywords.contains(where: { lowerSeg.contains($0) }) {
                amountSegmentType = .income
            } else if expenseKeywords.contains(where: { lowerSeg.contains($0) }) {
                amountSegmentType = .expense
            }
        }
        // 分类打分
        for (category, keywords) in categoryKeywords {
            for kw in keywords {
                if seg.contains(kw) {
                    categoryScores[category, default: 0] += 1
                }
            }
        }
    }
    // 4. 分类打分
    let bestCategory = categoryScores.max(by: { $0.value < $1.value })?.key ?? "其他"
    // 5. 类型判断
    let incomeCategories = ["工资"]
    let type: Transaction.TransactionType = amountSegmentType ?? (incomeCategories.contains(bestCategory) ? .income : .expense)
    // 6. 备注
    let note = text
    return (amount ?? 0.0, bestCategory, type, note)
}

// 提取字符串中的第一个数字（支持整数和小数）
func extractNumber(_ text: String) -> Double? {
    let pattern = "[0-9]+\\.?[0-9]*"
    if let regex = try? NSRegularExpression(pattern: pattern),
       let match = regex.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)),
       let range = Range(match.range, in: text) {
        return Double(text[range])
    }
    return nil
} 
